package com.csdj.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.server.config.JwtTokenUtil;
import com.csdj.server.mapper.AdminMapper;
import com.csdj.server.mapper.AdminRoleMapper;
import com.csdj.server.mapper.RoleMapper;
import com.csdj.server.pojo.Admin;
import com.csdj.server.pojo.AdminRole;
import com.csdj.server.pojo.RespBean;
import com.csdj.server.pojo.Role;
import com.csdj.server.service.IAdminService;
import com.csdj.server.util.AdminUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyq
 * @since 2022-12-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired(required = false)
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired(required = false)
    private RoleMapper roleMapper;
    //

    @Autowired(required = false)
    private AdminRoleMapper adminRoleMapper;

    @Override
    public RespBean login(String username, String password,String code,
                          HttpServletRequest request) {

        String captcha = (String) request.getSession()
                .getAttribute("captcha");
        //StringUtils
        //如果验证码 为空 或者 输入的验证码不一致
        if(StringUtils.isBlank(captcha)||!captcha.equals(code)){
            return RespBean.error("验证码填写错误!");
        }

        //security 自定义登录逻辑
        UserDetails userDetails =
                userDetailsService.loadUserByUsername(username);
        //通过 security 获取到用户信息
        //如果为null 或者 密码 是否一致
        if(userDetails==null||
                !passwordEncoder.matches(password,userDetails.getPassword()) ){

            return RespBean.error("用户名或密码不正确,请联系管理员");
        }
        //判断 账号 是否禁用 false 为禁用状态
        if(!userDetails.isEnabled()){
            return RespBean.error("账号已被禁用,请联系管理员");
        }
        //授权 处理
        // UsernamePasswordAuthenticationToken 授权信息
        //根据 用户信息 获取 令牌
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null,
                userDetails.getAuthorities());
        //拿到 一个全局的 SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成 token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> tokenMap=new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);

        return RespBean.success("登录成功",tokenMap);
    }

    /**
     * 根据 用户名 查询 用户信息
     * @param username
     * @return
     */
    @Override
    public Admin getAdminInfoByUserName(String username) {
             //=
        // select * from admin where username="admin"
        return adminMapper.selectOne(new QueryWrapper<Admin>()
                .eq("username",username));
    }

    @Override
    public List<Role> getRoles(Integer adminId) {

        return roleMapper.getRoles(adminId);
    }

    @Override
    public List<Admin> getAllAdmins(String keywords) {
        //id怎么获取 可以从security的全局对象中获取
       /* Integer id = ( (Admin) SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal()).getId();*/

     return adminMapper.getAllAdmins(
             AdminUtils.getCurrentAdmin().getId(),keywords);

    }

    /**
     * 操作员 更改 角色信息
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        //1.需要把原有的当前用户的 角色信息 先做删除
        adminRoleMapper.delete(new QueryWrapper<AdminRole>()
                .eq("adminId",adminId));
        //2.删除之后 添加新的角色信息
        Integer result = adminRoleMapper.addRole(adminId, rids);
        //受影响行数  等于 角色列表数组的总长度 添加成功
        if(result==rids.length){
            return RespBean.success("修改成功!");
        }
        return RespBean.error("修改失败!");
    }

    @Override
    public RespBean updatePassword(String oldPass, String password, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder passwordEncoder =
                new BCryptPasswordEncoder();
        //判断输入的旧密码是否正确
        if(passwordEncoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(passwordEncoder.encode(password));
            if(adminMapper.updateById(admin)==1){
                return RespBean.success("修改密码成功!");
            }
        }

        return RespBean.error("修改密码失败!");
    }

    @Override
    public RespBean updateAdminFace(String url, Integer id, Authentication authentication) {

        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);

        int result = adminMapper.updateById(admin);
        if(result==1){
            Admin  admins = (Admin) authentication.getPrincipal();
            admins.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(admin,authentication.getCredentials(),
                            authentication.getAuthorities()));

            return RespBean.success("修改头像成功!",url);
        }
        return RespBean.error("修改头像失败!");
    }
}
